// reference local blank image
// Ext.BLANK_IMAGE_URL = 'resource/s.gif';

Ext.ns('journal.home');

// create application
journal.home.Main = (function() {

    // do NOT access DOM from here; elements don't exist yet

    // private variables
    //    var main;
    var config = {};
    // private functions

    journal.Setup.init();

    // public space
    return {
        // public properties, e.g. strings to translate

        // public methods=====================================================================
        constructor : function(p_config) {
            config = p_config;
        },

        init : function() {
            /**
             * This callback method is to be called after a successful save in the editor panel.
             * 
             * @param branchId
             * @param entryId
             * @param text
             * @param create - boolean value to specify if the node is to be created in the tree (add) or not (update).
             */
            var callbackSaveEntry = function(branchId, entryId, text, create) {
                this.mainToolbar.get(journal.Constant.Button.SAVE).setDisabled(true);
                var fileMenu = this.menubar.get(journal.Constant.Menu.FILE);
                var fileSaveMenu = fileMenu.menu.items.get(journal.Constant.Menu.SAVE);
                fileSaveMenu.setDisabled(true);

                var tree = this.explorerPanel.get(journal.Constant.Id.ENTRY_TREE);
                var targetNode = tree.getNodeById(branchId);
                targetNode.on('append', function(tree, thisNode, appendedNode, index) {
                    if (create && appendedNode.isLeaf()) {
                        journal.home.MainHandler.addRecentFileItem(appendedNode);
                        journal.StateService.add(journal.StateService.ST_TAB, appendedNode.getPath());
                        journal.StateService.add(journal.StateService.ST_TABORDER, appendedNode.getPath());
                        thisNode.un('append');//To prevent from firing on move node.
                    }
                });

                if (create) {
                    var newNode = new Ext.tree.TreeNode({
                        id : 'l-' + entryId,
                        text : text,
                        leaf : true
                    });
                    newNode = targetNode.appendChild(newNode);
                    newNode.select();
                }
            }.createDelegate(this);

            var callbackNewItemTab = function() {
                var selectedNode = this.explorerPanel.codeExplorer.getSelectionModel().getSelectedNode();
                selectedNode.expand();
                this.editorPanel.newTabHandler(selectedNode);
            }.createDelegate(this);

            var viewport = new Ext.Viewport({
                name : 'mainvp',
                layout : 'border',
                renderTo : Ext.getBody(),

                items : [ new Ext.Panel({
                    id : journal.Constant.Id.TOPBAR,
                    height : 'auto',
                    region : 'north',
                    width : 100,
                    tbar : {
                        xtype : 'container',
                        layout : 'anchor',
                        height : 54,
                        defaults : {
                            height : 27,
                            anchor : '100%'
                        },
                        items : [ {
                            id : journal.Constant.Id.MENUBAR,
                            xtype : 'journal.home.Menubar',
                            user : config.user
                        }, {
                            id : journal.Constant.Id.TOOLBAR,
                            xtype : 'journal.home.MainToolbar',
                            user : config.user,
                            appVersion : config.appVersion
                        } ]
                    }
                }), {
                    id : journal.Constant.Id.NAVPANEL,
                    xtype : 'journal.home.ExplorerPanel',
                    region : 'west',
                    split : true,
                    collapsible : true,
                    width : 240
                }, {
                    id : journal.Constant.Id.EDITORPANEL,
                    xtype : 'journal.home.EntryEditorPanel',
                    region : 'center',
                    callbackSaveEntry : callbackSaveEntry
                } ]
            });// end of ViewPort

            this.mainToolbar = viewport.get(journal.Constant.Id.TOPBAR).getTopToolbar()
                    .get(journal.Constant.Id.TOOLBAR);
            this.menubar = viewport.get(journal.Constant.Id.TOPBAR).getTopToolbar().get(journal.Constant.Id.MENUBAR);
            this.explorerPanel = viewport.get(journal.Constant.Id.NAVPANEL);
            this.editorPanel = viewport.get(journal.Constant.Id.EDITORPANEL);
            this.explorerPanel.codeExplorer = this.explorerPanel.get(0);
            this.explorerPanel.codeExplorer.callbackNewItemTab = callbackNewItemTab;

            this.explorerPanel.codeExplorer.on('dblclick', function(node, event) {
                if (!node.isLeaf()) {
                    return;
                }

                var nodeTab = this.editorPanel.getNodeTab(node);
                if (!nodeTab) {
                    journal.home.MainHandler.addRecentFileItem(node);
                    new Ext.LoadMask(this.editorPanel.el.dom).show({
                        text : 'Loading editor... Please wait.'
                    });
                    this.editorPanel.newTabHandler(node);
                } else {
                    this.editorPanel.activate(nodeTab);
                }
            }.createDelegate(this));

            this.explorerPanel.codeExplorer.treeEditor.on('complete', function(ed, newValue, oldVal) {
                if (newValue == oldVal) {
                    return false;
                }
                if (newValue.indexOf('*') > -1) {
                    Ext.Msg.show({
                        icon : Ext.MessageBox.ERROR,
                        buttons : Ext.Msg.OK,
                        title : 'Validation Error',
                        msg : 'Invalid Title'
                    });
                    return false;
                } else {
                    this.explorerPanel.codeExplorer.el.mask('Saving...', 'x-mask-loading');
                    var selNode = ed.tree.getSelectionModel().getSelectedNode();
                    Ext.Ajax.request({
                        url : 'home?action=renameNode',
                        params : {
                            nodeId : selNode.id,
                            title : newValue,
                            oldTitle : oldVal,
                            isLeaf : selNode.isLeaf()
                        },
                        success : function(response) {
                            this.explorerPanel.codeExplorer.el.unmask();
                            var respObj = Ext.util.JSON.decode(response.responseText);
                            if (respObj.success) {
                                selNode.setText(respObj.title);
                                this.editorPanel.items.each(function(next) {
                                    if (next.node == selNode) {
                                        if (next.title.indexOf('*') > -1) {
                                            next.setTitle('*' + respObj.title);
                                        } else {
                                            next.setTitle(respObj.title);
                                        }
                                        next.get(0).getForm().findField('title').setValue(respObj.title);
                                        return false;
                                    }
                                }.createDelegate(this));

                            } else {
                                this.explorerPanel.codeExplorer.el.unmask();
                                journal.Utility.doStandardError(respObj);
                                selNode.setText(oldVal);
                            }
                        }.createDelegate(this),
                        failure : function(response) {
                            this.explorerPanel.codeExplorer.el.unmask();
                        }
                    });
                }
            }.createDelegate(this));

            this.mainToolbar.get(journal.Constant.Button.SAVE).on('click', function(btn) {
                this.editorPanel.saveTab(false);
            }.createDelegate(this));

            this.explorerPanel.codeExplorer.on('click',
                    function(selectedNode, event) {
                        selectedNode.ownerTree.treeEditor.cancelEdit();
                        var isRoot = selectedNode.text == 'Root';
                        var sbutton = this.mainToolbar.get(journal.Constant.SButton.NEW);

                        var fileMenu = this.menubar.get(journal.Constant.Menu.FILE);
                        var fileNewMenu = fileMenu.menu.items.get(journal.Constant.Menu.NEW);
                        fileNewMenu.menu.items.get(journal.Constant.Menu.NEW_ENTRY).setVisible(
                                !isRoot && !selectedNode.isLeaf());
                        sbutton.menu.items.get(journal.Constant.Button.NEW_ENTRY).setVisible(
                                !isRoot && !selectedNode.isLeaf());
                    }.createDelegate(this));

            this.editorPanel.on('tabchange', function(t, p) {
                journal.home.Main.explorerPanel.activeTab.treeEditor.cancelEdit();
                var fileMenu = this.menubar.get(journal.Constant.Menu.FILE);
                var fileSaveMenu = fileMenu.menu.items.get(journal.Constant.Menu.SAVE);
                if (p == null) {// fires when last tab is closed
                    this.mainToolbar.get(journal.Constant.Button.SAVE).setDisabled(true);
                    fileSaveMenu.setDisabled(true);
                    return;
                } else if (p.node == null) {//search tab
                    return;
                }
                if (p.node.isLeaf()) {
                    journal.StateService.putOnLast(journal.StateService.ST_TABORDER, p.node.getPath());
                }
                this.mainToolbar.get(journal.Constant.Button.SAVE).setDisabled(p.title.indexOf('*') == -1);
                fileSaveMenu.setDisabled(p.title.indexOf('*') == -1);

                var linkWithEditor = this.explorerPanel.codeExplorer.getTopToolbar().get('ce-linkweditor').pressed;
                if (linkWithEditor) {
                    var tree = this.explorerPanel.codeExplorer;
                    tree.selectPath(p.node.getPath());
                }
            }.createDelegate(this));

            Ext.EventManager.on(document, 'keypress', function(e) {
                journal.home.MainHandler.keyHandler(e, this);
            }.createDelegate(this));

            Ext.EventManager.on(document, 'keyup', function(e) {
                if (e.keyCode == e.ALT) {
                    e.stopEvent();
                }
            }.createDelegate(this));

            this.explorerPanel.codeExplorer.on('expandnode', function(node) {
                if (this.ready && node.text != 'Root' && !node.isLeaf()) {
                    journal.StateService.add(journal.StateService.ST_TREE, node.getPath());
                }
            }.createDelegate(this));
            this.explorerPanel.codeExplorer.on('collapsenode', function(node) {
                journal.StateService.remove(journal.StateService.ST_TREE, node.getPath());
            }.createDelegate(this));

            //Info: Begin restore from state =============================================================================
            journal.StateService.restore(journal.StateService.ST_RECENTLIST, function(nodeToken) {
                var nodeArr = nodeToken.split('|');
                journal.home.MainHandler.createMenuItem(nodeArr[0], nodeArr[1], this);
            }.createDelegate(this));
            journal.home.MainHandler.fixRecentItemIndex();

            //NOTE: restore do not trigger with a clear cookie, thus resulting on to permanent restoreFlag set to true   
            if (Ext.state.Manager.get(journal.StateService.ST_TREE) == null
                    || Ext.state.Manager.get(journal.StateService.ST_TREE).indexOf('/') == -1) {
                journal.StateService.restoreFlag = false;
            }

            this.ready = false;
            journal.StateService.restore(journal.StateService.ST_TREE, function(arg) {
                this.explorerPanel.codeExplorer.expandPath(arg);
            }.createDelegate(this));
            this.ready = true;

            setTimeout(function() {
                Ext.get('loading').remove();
                Ext.get('loading-mask').fadeOut({
                    remove : true
                });
            }, 500);

            Ext.Ajax.on('requestcomplete', function(conn, response, options) {
                if (response.responseXML == null && Ext.isGecko) {//session expired. login screen.
                    journal.Utility.showSessionExpired();
                    //infinite loop for safari and chrome
                }
            }, this);

        }// end of init()
    };
})(); // end of app
// end of file
